package frame.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import frame.form.ActionForm;
import frame.form.ConstructForm;
import frame.form.XmlBean;
import business.LoginAction;

public class ActionServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String disUrl = "";
		String path = this.getPath(req.getServletPath());
		Map<String,XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		System.out.println(path);
		XmlBean xmlBean = map.get(path);
		String formClass = xmlBean.getFormClass();
		ActionForm form = ConstructForm.construct(formClass, req);
		String actionClass = xmlBean.getHandler();
		Action action = null;
		try {
			Class clazz = Class.forName(actionClass);
			action = (Action) clazz.newInstance();
			disUrl = action.execute(req,resp,form,xmlBean.getActionForward());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestDispatcher dis = req.getRequestDispatcher(disUrl);
		dis.forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	private String getPath(String path){
		return path.split("\\.")[0];
	}
}
